//
//  MyPostRequest.m
//  PostDemo1
//
//  Created by  江志磊 on 15-1-29.
//  Copyright (c) 2015年  江 志磊. All rights reserved.
//

#import "MyPostRequest.h"

@implementation MyPostRequest{
    NSURLConnection *_urlConnection;
    NSMutableData *_downloadData;
    DownloadFinishedBlock _finishedBlock;
    DownloadFailedBlock _failedBlock;
}


- (void)requestWithUrlString:(NSString *)urlString parms:(NSDictionary *)dic contentType:(NSString *)type requestMethod:(NSString *)method finishedBlock:(DownloadFinishedBlock)finished failedBlock:(DownloadFailedBlock)failed{
  //实现post请求
    if (_finishedBlock) {
        //清除上一次的block
        _finishedBlock = nil;
    }
     _finishedBlock = finished;
    if (_failedBlock) {
        _failedBlock = nil;
    }
     _failedBlock = failed;
    NSURL *url = [NSURL URLWithString:urlString];
    //url 地址作为请求头信息
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式(GET/POST)
    [request setHTTPMethod:method];
    //设置Content-Type，告诉服务器，请求体参数的组织形式
    [request setValue:type forHTTPHeaderField:@"Content-Type"];
    NSMutableString *bodyString  =[NSMutableString string];
    NSInteger i=0;
    //将请求体参数通过key=value&key=value方式拼接起来
    for (NSString *key in dic) {
        id obj = [dic objectForKey:key];
        if (i==0) {
            [bodyString appendString:[NSString stringWithFormat:@"%@=%@",key,obj]];
        }else{
            [bodyString appendString:[NSString stringWithFormat:@"&%@=%@",key,obj]];
        }
        i++;
    }
    NSData *data = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    //将参数的length设置成Content-Length
    //HTTP头和Body都没有长度的要求。
    [request setValue:[NSString stringWithFormat:@"%d",data.length] forHTTPHeaderField:@"Content-Length"];
    
    //设置请求体(带有的是请求的参数)
    [request setHTTPBody:data];
    
    //上一次的连接存在，则取消并销毁
    if (_urlConnection) {
        [_urlConnection cancel];
        _urlConnection =nil;
    }
    _urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    //如果data没初始化，则执行初始化操作
    if (!_downloadData) {
        _downloadData  =[[NSMutableData alloc] init];
    }
    [_downloadData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [_downloadData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    if (_finishedBlock) {
        _finishedBlock(_downloadData);
    }
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    if (_failedBlock) {
        _failedBlock(error.localizedDescription);
    }
}




@end
